/// Ajax Busy
(function ($, undefined) {

    // define the name of the UI component
    var ui_name = "ajaxBusy"

    // initialize object
    var ab = $.ajaxBusy = {

        // default values
        defaults: {
            'sender': [],
            'disabledControls': [],
            'isOverlay': false,
            'timeOut': 15000 // 超时时间 默认15秒
        },

        setDefaults: function (defaultOptions) {
            this.defaults = $.extend({}, this.defaults, defaultOptions);
        }
    };

    $.fn.ajaxBusy = function (options) {
        var ajaxBusyDisabledControls = [];
        var ajaxBusyTimeoutId = 0;
        var ajaxBusyCount = 0;
        var AjaxBusyStaticResource = {
            'busy': '正在载入...'
        };

        var ajaxBusy_disabledControls = [];


        // method calling
        if (typeof options == 'string') {
            var args = Array.prototype.slice.call(arguments, 1),
			res;
            this.each(function () {
                var data = $.data(this, ui_name);
                if (data) {
                    var meth = data[options];
                    if (meth) {
                        var r = meth.apply(this, args);
                        if (res === undefined) {
                            res = r;
                        }
                    }
                }
            });
            if (res !== undefined) {
                return res;
            }
            return this;
        }

        // initialize options
        options = $.extend({}, ab.defaults, options);

        this.each(function () {
            var _self = this;

            // initialize callback
            for (var key in options) {
                var value = options[key];
                if (typeof value == 'function') {
                    // bind callbacks
                    $(_self).bind(key, value);
                }
            }



            /* Public Methods
            -----------------------------------------------------------------------------*/


            function ajaxBusyTimeout() {
                if (ajaxBusyCount > 0) {
                    // todo: 这里有问题，先取消超时功能
                    //alert('很长时间没有反应，系统出错了！！！');
                    endAjaxBusy();
                }
            };

            function getAjaxCover() {
                var divAjaxCover = $('#ajax-busy-cover');
				
                if (divAjaxCover.length == 0) {
                    divAjaxCover = $('<div id="ajax-busy-cover" class="ajax-busy" />')
                        .appendTo('body');
						
					var setAjaxCoverPosition = function (ajaxConverElement){
	                    var x = ($(window).width() - ajaxConverElement.outerWidth()) / 2 + 'px';
	                    ajaxConverElement.css({ left: x });
					};
						
                    // 居中显示坐标
					setAjaxCoverPosition(divAjaxCover);
					
					// such a stupid method
                    // 为了保证箭头位置准确，不断的重绘
                    setInterval(function () {
						setAjaxCoverPosition(divAjaxCover);
                    }, 50);

                    // 窗体大小变化时，自动重绘箭头
                    $(window).wresize(function () {
                        setAjaxCoverPosition(divAjaxCover);
                    });
					
                    divAjaxCover.html(AjaxBusyStaticResource['busy']);


                }
                return divAjaxCover;
            };



            function endAjaxBusy() {
                var divAjaxCover = getAjaxCover();
                $(ajaxBusy_disabledControls).each(function (index, item) {
                    $(item).attr('disabled', false);
                });

                divAjaxCover.remove();
                clearTimeout(ajaxBusyTimeoutId);
                ajaxBusyCount = 0;
            };




            /* Public Methods
            -----------------------------------------------------------------------------*/

            var publicMethods = {
                option: function (name, value) {
                    if (value === undefined) {
                        return options[name];
                    }
                    options[name] = value;
                },

                begin: function () {
                    var divAjaxCover = getAjaxCover();

                    //todo: 设置disabledcontrols
                    $(options.disabledControls).each(function (index, item) {
                        ajaxBusy_disabledControls.push(item);
                        $(item).attr('disabled', true);
                    });

                    ajaxBusyTimeoutId = setTimeout(ajaxBusyTimeout, options['timeOut']);
                    ajaxBusyCount++;
                },

                end: function () {
                    var divAjaxCover = getAjaxCover();
                    $(ajaxBusy_disabledControls).each(function (index, item) {
                        $(item).attr('disabled', false);
                    });

                    divAjaxCover.remove();
                    clearTimeout(ajaxBusyTimeoutId);
                    ajaxBusyCount = 0;
                }

                // @other public methods
            };

            $.data(this, ui_name, publicMethods);

        });

        return this;
    };

    // @static methods

})(jQuery);
